package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.dao.OrderSettingDao;
import com.itheima.pojo.OrderSetting;
import com.itheima.service.OrderSettingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import java.util.*;
/**
 * 预约设置服务
 */
@Service(interfaceClass = OrderSettingService.class)
@Transactional
public class OrderSettingServiceImpl implements OrderSettingService {
    @Autowired
    private OrderSettingDao orderSettingDao;
    //批量添加
    @Override
    public void add(List<OrderSetting> list) {
        if(list != null && list.size() > 0){
            for (OrderSetting orderSetting : list) {
                //检查此数据（日期）是否存在

                long count = orderSettingDao.findCountByOrderDate(orderSetting.getOrderDate());
                System.out.println(orderSetting.toString());
                System.out.println(count);
                if(count > 0){
                    //已经存在，执行更新操作

                    orderSettingDao.editNumberByOrderDate(orderSetting);
                }else{
                    //不存在，执行添加操作

                    orderSettingDao.add(orderSetting);
                }
            }
        }
    }

    @Override
    public List<Map> getOrderSettingByMonth(String date) {
        //查找的开始时间
        String dateBegin = date+"-1";
        //查找的结束时间
        String dateEnd = date+"-31";

        Map<String, String> map =new HashMap();
        map.put("dateBegin",dateBegin);
        map.put("dateEnd",dateEnd);

        //查找
        List<OrderSetting> list =orderSettingDao.getOrderSettingByMonth(map);
        //重新封装
        List<Map> data = new ArrayList<>();
        if (list!=null && list.size()>0){
            for (OrderSetting orderSetting : list) {
                Map orderSettingMap = new HashMap();
                //获得日期（几号）
                orderSettingMap.put("date", orderSetting.getOrderDate().getDate());
                //可预约人数
                orderSettingMap.put("number",orderSetting.getNumber());
                //已预约人数
                orderSettingMap.put("reservations",orderSetting.getReservations());
                //添加到目标集合
                data.add(orderSettingMap);
            }
        }
        return data;
    }

    //根据日期修改可预约人数
    @Override
    public void editNumberByDate(OrderSetting orderSetting) {
        //因为有两种情况得判断，有数据-->修改，没数据-->添加
        //根据日期查询有没有预约，大于零-->有预约，调修改
        long count = orderSettingDao.findCountByOrderDate(orderSetting.getOrderDate());
        if (count>0) {
            //有预约，调修改
            orderSettingDao.editNumberByOrderDate(orderSetting);
        }else {
            //无预约，调新增
            orderSettingDao.add(orderSetting);
        }
    }
}